package main

import (
	"fmt"
	"go-web-learning/src/02_message_system/02_message_system/chatroom/common/netWork"
	"go-web-learning/src/02_message_system/02_message_system/chatroom/server/model"
	"io"
	"time"
)

func main() {
	fmt.Println("服务器在9805端口监听.....")
	listen, err := netWork.Listen("tcp", "0.0.0.0:9805")
	if err != nil {
		fmt.Println("net listen err:", err)
		return
	}
	defer listen.Close()
	for {
		fmt.Println("等待客户端连接服务器......")
		conn, err := listen.Accept()
		if err != nil {
			fmt.Println("listen accept err:", err)
		} else {
			go process(conn)
		}
		// 启动协程和客户端保持链接
	}
}

func init() {
	// 初始化redis连接池
	initPool("0.0.0.0:6379", 16, 0, 300*time.Second)
	initUserDao()
}

func initUserDao() {
	model.MyUserDao = model.NewUserDao(pool)
}

// 处理和客户端的链接
func process(conn netWork.Conn) {
	defer conn.Close()
	// 读取客户端发送的信息
	p := Processor{Conn: conn}
	err := p.Process()
	if err == io.EOF {
		fmt.Println("客户端关闭链接了，服务器端正常退出")
		return
	} else if err != nil {
		fmt.Println("readPkg fail, err:", err)
		return
	}
}
